import axios from 'axios';
import { PaginateConfig, PaginateResult } from '@/type/Shared';
import { objectToParams } from '@/helpers/AxiosHelper';
import { Permission, Role } from '@/type/Permission';
import { getAuth } from '.';

async function hasPermission(permission: string): Promise<boolean> {
    return axios.get(`/permissions/${permission}`, getAuth());
}

async function assistUserRole(userId: number, roles: Role[]): Promise<boolean> {
    return axios.put(`/users/${userId}/roles`, { roles }, getAuth());
}

async function getRoles(config: PaginateConfig): Promise<PaginateResult<Role[]>> {
    return axios.get(`/roles?${objectToParams(config)}`, getAuth());
}

async function getRole(id: number): Promise<Role> {
    return axios.get(`/roles/${id}`, getAuth());
}

async function createRole(role: Role, permissions: number[]): Promise<Role> {
    return axios.post('/roles', { role, permissions }, getAuth());
}

async function updateRole(role: Role, permissions: number[]): Promise<Role> {
    return axios.put(`/roles/${role.id}`, { role, permissions }, getAuth());
}

async function deleteRole(id: number): Promise<boolean> {
    return axios.delete(`/roles/${id}`, getAuth());
}

async function getPermissions(config: PaginateConfig): Promise<PaginateResult<Permission[]>> {
    return axios.get(`/permissions?${objectToParams(config)}`, getAuth());
}

export default {
    hasPermission,

    assistUserRole,

    getRoles,
    getRole,
    createRole,
    updateRole,
    deleteRole,

    getPermissions,
};
